<template>
    <div ref="chartRef" style="width: 100%; height: 210px" />
</template>

<script lang="ts" setup>
import { onMounted, ref, toRefs, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import charts1 from '@/assets/xj/charts1.png'
import { getCurrentDate } from "@/utils/date";

// 监听父组件传入的 scale
const props = defineProps<{
  scale: number;
}>();

const chartRef = ref()
let chart: any

// 横坐标标签
const labels = ['5分钟雨量', '当日雨量', '当月雨量', '本年雨量']
const resData = ref([])

/**
 * 获取当前日期
 */
function getYesterdayFormatted() {
  const today = new Date();
  today.setDate(today.getDate() - 1);
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, '0');
  const day = String(today.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/**
 * 请求数据并渲染图表
 */
const rainfallData = () => {
  const time = getYesterdayFormatted();
  fetch(`http://111.51.78.52:8009/dataservice/apiInfo/queryData/ads_nx_cc_reservoir_rainfall?datadate=${time}`, {
    headers: {
      "app_id": "c87ed68a-58d0-453e-a6f0-6c744f1262ed",
      "app_key": "e52156d990f2fed36b4624d294dbfafa-1687331173382-640715"
    },
  })
    .then((r) => r.status === 200 ? r.json() : Promise.reject(r.json()))
    .then((res) => {
      const resData = res.data[0] || {};

      // 构造纵坐标数据：与 labels 顺序对应
      const values = [
        Number(resData.min5_rainfall).toFixed(2) || 0,
        Number(resData.today_rainfall).toFixed(2) || 0,
        Number(resData.monthly_rainfall).toFixed(2) || 0,
        Number(resData.yearly_rainfall).toFixed(2) || 0
      ];

      resData.value = values

      renderCylinderChart(labels, values);
    });
}

const renderCylinderChart = (labels: string[], values: number[]) => {
      chart = echarts.init(chartRef.value, undefined, {
    devicePixelRatio: window.devicePixelRatio * (props.scale || 1),
  });
  const barWidth = 12
  const symbolSize = [barWidth, 6]
  const ellipsePath = 'path://M0,8 A8,8 0 1,0 16,8 A8,8 0 1,0 0,8 Z'
const max = Math.max(...values.map(Number)) || 10
const interval = Math.ceil(max / 4)
  const option = {
    grid: { left: 30, right: 50, top: 30, bottom: 100 },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: labels,
      axisTick: { show: false },
      axisLine: { show: true },
      axisLabel: { color: '#fff', fontSize: 12 },
    },
    yAxis: {
      name: '单位：毫米',
      axisLine: { show: false },
      axisTick: { show: false },
      max: interval * 4,
      interval, 
      splitNumber: 4,
      nameTextStyle: {
        color: '#fff', // 👈 设置字体颜色为白色
        fontSize: 12,  // 可选：设置字体大小
        fontWeight: 'normal' // 可选：字体粗细
      },
      splitLine: {
        show: true,
        lineStyle: { color: '#fff', type: 'dashed' },
      },
      axisLabel: { color: '#fff' },
    },
    series: [
      {
        type: 'pictorialBar',
        symbol: `image://${charts1}`,
        symbolSize: [23, 11],
        symbolOffset: [0, '50%'],
        z: 1,
        data: values.map(() => 0),
        tooltip: { show: false }
      },
      {
        name: '值',
        type: 'bar',
        barWidth,
        data: values,
        z: 3,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#38e8ee' },
            { offset: 0.5, color: '#22bedd' },
            { offset: 1, color: '#0a89c2' },
          ]),
          borderRadius: [1, 1, 0, 0],
        },
        tooltip: { show: false }
      },
      {
        type: 'pictorialBar',
        symbol: ellipsePath,
        symbolSize,
        symbolPosition: 'end',
        symbolOffset: ['0', '-30%'],
        z: 4,
        data: values,
        itemStyle: {
          color: '#1ad0db',
          opacity: 1,
        },
      },
      {
        type: 'pictorialBar',
        symbol: ellipsePath,
        symbolSize,
        symbolOffset: [0, '50%'],
        z: 1,
        data: values.map(() => 0),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#38e8ee' },
            { offset: 0.5, color: '#22bedd' },
            { offset: 1, color: '#0a89c2' },
          ]),
          opacity: 1,
        },
        tooltip: { show: false }
      },
    ],
  }

  chart.setOption(option)
}

const resizeChart = (): void => {
  if (chart) {
    chart.resize();
  }
};

watch(
  () => props.scale,
  () => {
    if (chart) {
      nextTick(() => {
        chart?.dispose();
       renderCylinderChart(labels, resData);
      });
    }
  }
);

onMounted(() => {
  chart = echarts.init(chartRef.value)
  rainfallData()
  window.addEventListener('resize', resizeChart);
})

</script>
